import {Component, OnInit} from '@angular/core';
import {SERVER_URL} from '../../config';
import {HttpClient} from '@angular/common/http';
import {NbToastStatus} from '@nebular/theme/components/toastr/model';
import {NbToastrService} from '@nebular/theme';
import {NbDialogRef} from '@nebular/theme';
import {DateFormatter} from '@angular/common/src/pipes/deprecated/intl';

export interface ReturnData {
  ret: number;
  data: any;
  msg: string;
}

@Component({
  selector: 'app-produce-add',
  templateUrl: './produce-add.component.html',
  styleUrls: ['./produce-add.component.css']
})
export class ProduceAddComponent implements OnInit {
  foods: any;
  manufactures: any;
  manualReady: any = {
    food: '',
    manufacture: '',
    batch: '',
    qty: '',
    produceTime: '',
    listingTime: '',
  };

  constructor(private http: HttpClient, private toastrService: NbToastrService, protected dialogRef: NbDialogRef<any>) {
    this.loadData();
  }

  ngOnInit() {
  }

  close() {
    this.dialogRef.close();
  }

  async loadData() {
    const foodsReturnData = await this.http.get<ReturnData>(SERVER_URL + '?s=App.foodinfo.Select').toPromise();
    const manufacturesReturnData = await this.http.get<ReturnData>(SERVER_URL + '?s=App.manufacturer.Select').toPromise();
    if (foodsReturnData && manufacturesReturnData) {
      this.foods = foodsReturnData.data.code;
      this.foods = this.foods.filter(f => {
        if (f.Fcondition === '审核通过') {
          return f;
        }
      });
      this.manufactures = manufacturesReturnData.data.code;
      this.manufactures = this.manufactures.filter(m => {
        if (m.Fcondition === '审核通过') {
          return m;
        }
      });
      console.log(this.foods);
      console.log(this.manufactures);
    }
  }

  submit() {
    const formData = new FormData();
    formData.append('Batch', this.manualReady.batch);
    formData.append('FoodId', this.manualReady.food);
    formData.append('Listing_date', this.transDate(this.manualReady.listingTime));
    formData.append('Produce_date', this.transDate(this.manualReady.produceTime));
    formData.append('Qty', this.manualReady.qty);
    formData.append('FMId', this.manualReady.manufacture);
    this.http.post<ReturnData>(SERVER_URL + '?s=App.manualready.Insert', formData).subscribe(data => {
        console.log(data);
        if (data.ret === 200) {
          this.dialogRef.close('success');
          this.toastrService.show('添加成功', '提示', {status: NbToastStatus.SUCCESS});
        }else {
          this.toastrService.show('添加失败，请填写合规参数', '提示', {status: NbToastStatus.SUCCESS});
        }
    });
    console.log(this.manualReady);
  }
  transDate(time) {
    time.setMinutes(time.getMinutes() - time.getTimezoneOffset());
    return time.toISOString().substring(0, 10);
  }

}
